package com.hzlx.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hzlx.dto.InventoryRequest;
import com.hzlx.dto.InventoryResponse;
import com.hzlx.dto.ResultDto;
import com.hzlx.service.InventoryService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/inventory")
@Slf4j
public class InventoryController {
    @Resource InventoryService inventoryService;
    @PostMapping("/isInStock")
    @ResponseStatus(HttpStatus.OK)
    public ResultDto<List<InventoryResponse>> isInStockMap(@RequestBody List<Map<String,Object>> skus) {
        ObjectMapper objectMapper = new ObjectMapper(); // jackson
        List<String> skuList = skus.stream().map(map->{
            try {
                return objectMapper.writeValueAsString(map); // json
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }).collect(Collectors.toList());
        List<InventoryResponse> result = inventoryService.isInStock(skuList);
        log.info("接收库存检查skuCode: {}, 结果： {}", skuList, result);
        return ResultDto.<List<InventoryResponse>>builder().code("ok").data(result).build();
    }
    @ResponseStatus(HttpStatus.CREATED)
    @PostMapping
    public void create(@RequestBody InventoryRequest inventoryRequest){
        inventoryService.create(inventoryRequest);
    }

    @ResponseStatus(HttpStatus.OK)
    @PutMapping
    public void update(@RequestBody List<InventoryRequest> requests){
        requests.stream().forEach(request->inventoryService.update(request));
    }

}
